package com.example.xuanke.controller;

import com.example.xuanke.pojo.Result;
import com.example.xuanke.pojo.User;
import com.example.xuanke.service.UserService;
import com.example.xuanke.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(String username,String pwd){
        if (userService.isExist(username,pwd)){
            User user = userService.findByUsername(username);
            Map<String, Object> claims = new HashMap<>();
            claims.put("id",user.getId());
            claims.put("username",username);
            claims.put("password",pwd);
            String token = JwtUtil.genToken(claims);
            return Result.success("登录成功",token);
        }else {
            return Result.error("登陆失败");
        }
    }

    @PostMapping("/register")
    public Result register(String username,String pwd){
        if (userService.find(username)==0){
            userService.register(username,pwd);
            return Result.success("注册成功",username);
        }else {
            return Result.error("注册失败");
        }
    }
}
